<?php

namespace iflow\template\Adapter\Regx\implement\Tag;

use iflow\template\Adapter\Regx\implement\Abstracts\TagAbstract;
use iflow\template\Adapter\Regx\Interfaces\TagInterface;

class DbTag extends TagAbstract {

    // 查询语句
    protected string $sql = "";

    // 查询方法
    protected string $queryAction = "";

    // 查询模型
    protected string $queryModel = "";
    protected string $parameterName = "";

    public function parser(string $tag, string $html, array $args): TagInterface {
        parent::parser($tag, $html, $args); // TODO: Change the autogenerated stub

        $this->sql = $this->attrs['sql'] ?? '';
        $this->parameterName = $this->setParamsStartCode($this->attrs['parameterName'] ?? '');
        $this->queryModel = $this->attrs['model'] ?? '';
        $this->queryAction = $this->attrs['action'] ?? 'query';

        return $this;
    }


    /**
     * 生成PHP模板代码
     * @return string
     */
    public function toHtml(): string {

        $this->html .= "<?php ";
        $this->html .= $this->parameterName ? "{$this -> parameterName} = " : "";
        $props = $this -> props ? "...[{$this -> props}]" : "";

        if ($this->sql) {
            $this->html .= "\\think\\facade\\Db::{$this -> queryAction}(\"{$this->sql}\", $props)";
        } else if ($this->queryModel) {
            $this->html .= "app('{$this -> queryModel}') -> {$this -> queryAction}($props)";
        }
        $this->html .= ";?>";

        if ($this->source) {
            $this->html = $this->html . $this->source;
        }

        return parent::toHtml(); // TODO: Change the autogenerated stub
    }


}